package com.egg.ylt.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.egg.ylt.R;
import com.egg.ylt.Utils.API;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.CustomUtils;
import com.egg.ylt.Utils.StatusBarUtil;
import com.egg.ylt.Utils.StringUtil;
import com.egg.ylt.pojo.GetTitleByidEntity;
import com.egg.ylt.presenter.impl.NewsDetailsPresenterImpl;
import com.egg.ylt.view.INewsDetailsView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;
import com.yonyou.framework.library.base.BaseActivity;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.utils.ToastUtil;
import com.yonyou.framework.library.dialog.AlertDialog;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

public class ACT_NewsDetails extends BaseActivity<NewsDetailsPresenterImpl> implements INewsDetailsView {

    @BindView(R.id.news_details_iv_back)
    ImageView newsDetailsIvBack;
    @BindView(R.id.news_details_tv_title)
    TextView newsDetailsTvTitle;
    @BindView(R.id.news_details_iv_share)
    ImageView newsDetailsIvShare;
    @BindView(R.id.news_details_iv_collect)
    ImageView newsDetailsIvCollect;
    @BindView(R.id.news_details_rl_top)
    RelativeLayout newsDetailsRlTop;
    @BindView(R.id.webveiw_news)
    WebView webveiwNews;
    @BindView(R.id.target_view_ll)
    LinearLayout llTargetView;

    private String id;
    private AlertDialog shareDialog;
    private String webUrl;
    private boolean collectType;
    private String mTitle;
    private String content;

    @Override
    protected void getBundleExtras(Bundle extras) {
        id = extras.getString("id");
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_news_details;
    }

    @Override
    protected View getLoadingTargetView() {
        return llTargetView;
    }

    @Override
    protected void initViewsAndEvents() {

        StatusBarUtil.setStatusBarColor(this, R.color.ylt_whit);
        StatusBarUtil.StatusBarLightMode(this);
        CustomUtils.setImmersiveStatusBar(mContext, newsDetailsRlTop);

        //初始化webveiw
        WebSettings settings = webveiwNews.getSettings();

        webveiwNews.setWebViewClient(new WebViewClient());
        webveiwNews.setWebChromeClient(new WebChromeClient());
//        //因为分享授权中需要使用一些对应的权限
//        if(Build.VERSION.SDK_INT>=23){
//            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission
// .ACCESS_FINE_LOCATION,Manifest.permission.CALL_PHONE,Manifest.permission.READ_LOGS,Manifest.permission
// .READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.SET_DEBUG_APP,Manifest
// .permission.SYSTEM_ALERT_WINDOW,Manifest.permission.GET_ACCOUNTS,Manifest.permission.WRITE_APN_SETTINGS};
//            ActivityCompat.requestPermissions(this,mPermissionList,123);
//        }

        //请求资讯详情
        mPresenter.getNews(Constants.TOKEN, id);
    }


    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @Override
    public void getNewsDetails(GetTitleByidEntity entity) {
        if (entity == null) {
            return;
        }
        //0是未收藏  1是收藏
        String getCollect = entity.getGetCollect();
        if ("0".equals(getCollect)) {
            collectType = false;
            newsDetailsIvCollect.setSelected(false);
        } else {
            collectType = true;
            newsDetailsIvCollect.setSelected(true);
        }
        mTitle = entity.getTitle();
        webUrl = entity.getWebUrl();
        content = entity.getSubTitle();
        webveiwNews.loadUrl(webUrl);
    }

    @Override
    public void setCollectMessage() {
        collectType = true;
        newsDetailsIvCollect.setSelected(true);
        ToastUtil.makeText(mContext, "收藏成功", false);
    }

    @Override
    public void setCancelMessage() {
        collectType = false;
        newsDetailsIvCollect.setSelected(false);
        ToastUtil.makeText(mContext, "取消收藏", false);
    }

    @OnClick({R.id.news_details_iv_back, R.id.news_details_iv_collect, R.id.news_details_iv_share})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.news_details_iv_back:
                finish();
                break;
            case R.id.news_details_iv_collect://收藏
                if (StringUtil.isEmpty(Constants.TOKEN)) {
                    readyGo(ACT_UserLogin.class);
                    return;
                }
                if (collectType) {
                    mPresenter.setCancelMessage(Constants.TOKEN, id);
                } else {
                    mPresenter.setCollectMessage(Constants.TOKEN, id, Constants.COMPANYID);
                }
                break;
            case R.id.news_details_iv_share://分享
                //调用友盟的分享弹出框
//                new ShareAction(mContext).withText("hello")
//                        .setDisplayList(SHARE_MEDIA.SINA,SHARE_MEDIA.QQ,SHARE_MEDIA.QZONE,SHARE_MEDIA.WEIXIN,
// SHARE_MEDIA.WEIXIN_CIRCLE)
//                        .setCallback(shareListener).open();
                //调用自定义的分享弹出框
                umShareDialogShow();
                break;
        }
    }

    /**
     * 分享的dialog展示
     */
    public void umShareDialogShow() {
        //判断不为空直接关闭
        if (shareDialog != null) {
            shareDialog.dismiss();
        }

        shareDialog = new AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_um_share_view)
                .setCancelableOntheOutside(true)
                .setWidthAndHeight(mScreenWidth, 900)
                .fromBottom(true)
                .create();
        //设置点击事件
        //微信好友
        shareDialog.setOnClickListener(R.id.btn_share_wx, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isInstallByread("com.tencent.mm")) {
                    ShareNews(SHARE_MEDIA.WEIXIN);
                } else {
                    ToastUtil.makeText(mContext, "微信未安装", false);
                }
            }
        });
        //QQ空间
        shareDialog.setOnClickListener(R.id.btn_share_qq_space, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isInstallByread("com.tencent.mobileqq")) {
                    ShareNews(SHARE_MEDIA.QZONE);
                } else {
                    ToastUtil.makeText(mContext, "QQ应用未安装", false);
                }
            }
        });
        //新浪微博
        shareDialog.setOnClickListener(R.id.btn_share_sina, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareNews(SHARE_MEDIA.SINA);
            }
        });
        //QQ好友
        shareDialog.setOnClickListener(R.id.btn_share_qq_friend, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isInstallByread("com.tencent.mobileqq")) {
                    ShareNews(SHARE_MEDIA.QQ);
                } else {
                    ToastUtil.makeText(mContext, "QQ应用未安装", false);
                }
            }
        });
        //微信朋友圈
        shareDialog.setOnClickListener(R.id.btn_share_circle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isInstallByread("com.tencent.mm")) {
                    ShareNews(SHARE_MEDIA.WEIXIN_CIRCLE);
                } else {
                    ToastUtil.makeText(mContext, "微信未安装", false);
                }
            }
        });
        //取消dialog
        shareDialog.setOnClickListener(R.id.btn_share_cancel, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (shareDialog != null) {
                    shareDialog.dismiss();
                }
            }
        });
        //展示
        shareDialog.show();

    }

    /**
     * 友盟分享的界面
     *
     * @param shareId
     */
    public void ShareNews(SHARE_MEDIA shareId) {

        //友盟分享链接的对象
        String uri = API.SHARE_URI + "?id=" + id;
        final UMWeb web = new UMWeb(uri);//分享链接
        web.setTitle(mTitle);//标题
        web.setDescription(content);//描述

        new ShareAction(mContext)
                .setPlatform(shareId)//传入平台
                .withMedia(web)//分享链接
                .setCallback(shareListener)//回调监听器
                .share();
    }

    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(mContext, "分享成功", Toast.LENGTH_LONG).show();
            //判断不为空直接关闭
            if (shareDialog != null) {
                shareDialog.dismiss();
            }
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(mContext, "分享失败", Toast.LENGTH_LONG).show();
            //判断不为空直接关闭
            if (shareDialog != null) {
                shareDialog.dismiss();
            }
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
//            if (platform.getName().equals(SHARE_MEDIA.QQ)){
//
//            }else{
//                Toast.makeText(mContext,"取消分享",Toast.LENGTH_LONG).show();
//            }
            //判断不为空直接关闭
            if (shareDialog != null) {
                shareDialog.dismiss();
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 判断是否安装目标应用
     *
     * @param packageName 目标应用安装后的包名
     * @return 是否已安装目标应用
     */
    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }
}
